import { FastifyReply, FastifyRequest } from 'fastify';
import { Controller, GET, POST } from 'fastify-decorators';
import { z } from "zod";
import { app } from '..';
import userTokenService from '../service/userToken.service';


@Controller({ route: '/user' })
export default class AuthController {
    @GET('/info')
    async getUserInfo(request: FastifyRequest, reply: FastifyReply) {
        const user = await app.prisma.user.findFirst({
            where: {id: +request.user.id},
            include: {
                userSubscription: {where: {endDate: {gte: new Date()}}},
                userApiCall: true,
                tokens: true
            },
        });
        return app.json(user);
    }

    @GET('/token')
    async signInHandle(request: FastifyRequest, reply: FastifyReply) {
        const userToken = await userTokenService.query({userId: +request.user.id});
        return app.json(userToken);
    }

    @POST('/token/regenerate')
    async createToken(request: FastifyRequest, reply: FastifyReply) {
        const token = await app.prisma.$transaction(async (tx) => {
            const {token} = z.object({token: z.string()}).parse(request.body);
            const user = await app.prisma.user.findUnique({where: {id: +request.user.id}});
            if (!user) {
                throw new Error('user not exist');
            }
            const tokenRes =  userTokenService.generate({ email: user.email });
            const tokenRet = await tx.userToken.update({where: {token}, data: {token: tokenRes}});
            return tokenRet;
        });
        return app.json(token);
    }

    @GET('/call/history')
    async getCallHistory(request: FastifyRequest, reply: FastifyReply) {
        const userToken = await app.prisma.userApiCall.findMany({where: {userId: +request.user.id}});
        return app.json(userToken);
    }

    @GET('/subscriptionPlan/history')
    async getSubscriptionPlanHistory(request: FastifyRequest, reply: FastifyReply) {
        const userToken = await userTokenService.query({userId: +request.user.id});
        return app.json(userToken);
    }
}